package com.cweb.framework.exception;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.cweb.framework.pojo.BaseResponse;
import com.cweb.framework.pojo.CustomException;
import com.cweb.framework.util.ErrorEnum;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.HttpURLConnection;

@ControllerAdvice
public class GlobalDefaultExceptionHandler {
    private static final Log log = LogFactory.get();

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public BaseResponse defaultExceptionHandler(HttpServletRequest req, HttpServletResponse res, Exception e) {
        Throwable caseThrowable = e;
        while (null != caseThrowable) {
            System.out.println(caseThrowable.toString());
            // jdbc连接失败
            if (caseThrowable instanceof CannotGetJdbcConnectionException) {
                log.error("---------请求异常结束(jdbc连接失败)------");
                return BaseResponse.errorMessage(ErrorEnum.COMM_DB_JDBC_NULL.getCode(), ErrorEnum.COMM_DB_JDBC_NULL.getMsg());
            }
            // 用户未登录或者过期时，返回401
            if (caseThrowable instanceof CustomException) {
                CustomException myCustomException = (CustomException) e;
                if (myCustomException.getCode().equals(ErrorEnum.USER_LOGIN_TOKEN_NULL.getCode())
                        || myCustomException.getCode().equals(ErrorEnum.USER_LOGIN_TOKEN_TIMEOUT.getCode())) {
                    res.setStatus(HttpURLConnection.HTTP_UNAUTHORIZED);
                }
                log.error(e.getMessage());
                log.error("---------请求异常结束------");
                return BaseResponse.errorMessage(myCustomException.getCode(), myCustomException.getMessage());
            }
            caseThrowable = caseThrowable.getCause();
        }
        log.error(e);
        log.error("---------请求异常结束---------");
        return BaseResponse.errorMessage(ErrorEnum.COMM_ERROR.getCode(), ErrorEnum.COMM_ERROR.getMsg());
    }
}
